<template>
  <div class="app-container">
    <!-- mock 设置 -->
    <el-row>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>mock 设置</span>
        </div>
        <div style="width: 100%">
          <el-alert close-text="Get!" style="margin-bottom: 10px" title="mock" type="info">
            <div>1、mock 的本质在于模拟三方业务接口的返回，来满足自身的测试功能，快速完成测试任务；</div>
            <div>2、前置 url：每个项目有不同的前置 url，通过前置 url 来区分不同项目；</div>
            <div>3、如果你的 agent ip 是 192.168.1.1，agent 启动端口是 6625，前置 url 是 abc，接口地址是 /user/login，那最后生成的 mock 地址是 http://192.168.1.1:6625/mock/abc/user/login</div>
            <div>4、转发模式 - 不转发：只在平台查找 mock 返回，没找到直接返回；</div>
            <div>5、转发模式 - 接口未定义：当未查到此接口定义的 url 时，将请求转发到指定 url；</div>
            <div>6、转发模式 - 条件未定义：当未查到此接口定义的 url 和查到此接口定义的 url，但没匹配上条件时，都会将请求转发到指定 url。</div>
          </el-alert>
          <el-form ref="ProjectForm" :model="projectInfo" :rules="projectInfoRules" label-position="right" label-width="160px">
            <el-form-item label="" prop="desc">
              <el-switch
                v-model="projectInfo.mock"
                active-color="#13ce66"
                active-text="启用"
                inactive-color="#ff4949"
                inactive-text="停用"
                style="display: block"
              />
            </el-form-item>
            <el-row>
              <el-col :span="2">
                <el-form-item label="前置 url" label-width="65px" />
              </el-col>
              <el-col :span="22">
                <el-form-item label="/mock/" label-width="60px">
                  <el-input v-model="projectInfo.mockPreUrl" :disabled="!projectInfo.mock" placeholder="请输入 mock 前置 url" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="转发模式" prop="desc">
              <el-row>
                <el-col :span="4">
                  <el-select v-model="projectInfo.forwardMode" :disabled="!projectInfo.mock" placeholder="请选择转发模式" style="width: 100%">
                    <el-option v-for="item in forwardModeOptions" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-col>
                <el-col :span="20">
                  <el-input v-model="projectInfo.forwardUrl" :disabled="!projectInfo.mock || projectInfo.forwardMode===0" placeholder="转发 url" />
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
          <div style="text-align: center">
            <el-button type="primary" @click="updateProjectInfo()">保 存</el-button>
          </div>
        </div>
      </el-card>
    </el-row>

    <!-- 项目机器人 -->
    <el-row style="margin-top: 50px;">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>项目机器人</span>
        </div>
        <div style="text-align: right">
          <el-button-group style="margin-bottom: 4px;">
            <el-tooltip :open-delay="500" content="添加机器人" placement="top">
              <el-button icon-class="skill" size="mini" type="primary" @click="handleRobotCreate()"><i class="el-icon-plus" /></el-button>
            </el-tooltip>
          </el-button-group>
        </div>
        <el-table
          v-loading="listLoading"
          :data="robotListData"
          border
          element-loading-text="Loading"
          fit
          highlight-current-row
        >
          <el-table-column align="center" label="ID" width="95">
            <template v-slot="{row}">
              {{ row.id }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="机器人名称" width="200">
            <template v-slot="{row}">
              {{ row.name }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="机器人类型" width="130">
            <template v-slot="{row}">
              {{ robotNameConvert(row.type) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="机器人Hook">
            <template v-slot="{row}">
              {{ row.robotToken }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="更新时间" width="200">
            <template v-slot="{row}">
              <span> {{ row.updatedAt | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }} </span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="150">
            <template v-slot="{row, $index}">
              <el-button size="small" type="primary" @click="handleRobotUpdate(row)">修改</el-button>
              <el-button size="small" type="danger" @click="delRobot(row, $index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-row>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="robotDialogFormVisible" width="800px" :close-on-click-modal="false">
      <el-form ref="robotDataForm" :model="robotTemp" :rules="rebotRules" label-position="right" label-width="110px">
        <el-form-item label="机器人类型">
          <el-select v-model="robotTemp.type" placeholder="请选择机器人类型">
            <el-option
              v-for="item in rebotOptions"
              :key="item.id"
              :disabled="item.disabled"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="机器人名称" prop="name">
          <el-input v-model="robotTemp.name" placeholder="请输入机器人名称" />
        </el-form-item>
        <el-form-item label="机器人Hook" prop="robotToken">
          <el-input v-model="robotTemp.robotToken" placeholder="填写机器人的 WebHook，可在机器人设置页面查看，机器人用于报告通知" />
        </el-form-item>
        <el-form-item label="机器人密钥" prop="robotSecret">
          <el-input v-model="robotTemp.robotSecret" placeholder="（可选）填写机器人的密钥，可在机器人设置页面查看" show-password />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="robotDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createRobot():updateRobot()">确定</el-button>
      </div>
    </el-dialog>

    <!-- 访问令牌 - Token -->
    <el-row style="margin-top: 50px;">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>访问令牌 - Token</span>
        </div>
        <div style="width: 100%">
          <el-alert style="margin-bottom: 10px" title="请求 REST API 接口是需要设置的 访问令牌（Token）" type="info" show-icon close-text="Get!" />
          <el-form ref="dataForm" :model="temp" label-position="left" label-width="80px">
            <el-form-item label="过期天数" style="margin-bottom: 30px;">
              <el-input-number v-model="token.day" :step="180" />
            </el-form-item>
            <el-form-item label="Token" style="margin-bottom: 30px;">
              <el-input v-model="token.value" :rows="4" placeholder="Token 生成结果，生成后从这里复制" type="textarea" />
            </el-form-item>
          </el-form>
          <div style="text-align: center">
            <el-button type="primary" @click="importTestcase()">生成 Token</el-button>
          </div>
        </div>
      </el-card>
    </el-row>
  </div>
</template>

<script>
import { generateToken } from '@/api/user'
import { update as projectUpdate, selectById as projectSelectById } from '@/api/manage/project'
import { listAll as robotList, add as robotAdd, update as robotUpdate, del as robotDel } from '@/api/project/robot'

export default {
  data() {
    return {
      robotListData: null,
      listLoading: true,
      robotDialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      robotTemp: {
        name: ''
      },
      token: {
        value: '',
        day: 180
      },
      importLoading: false,
      projectInfo: {},
      temp: {},
      rebotOptions: [
        { id: 1, name: '钉钉机器人' },
        { id: 2, name: '企业微信机器人', disabled: true },
        { id: 3, name: '飞书机器人', disabled: true },
        { id: 4, name: '友空间机器人', disabled: true },
        { id: 5, name: '邮件', disabled: true }
      ],
      forwardModeOptions: [ // 转发模式 options
        {
          value: 0,
          label: '不转发'
        }, {
          value: 1,
          label: '接口未定义'
        }, {
          value: 2,
          label: '条件未定义'
        }
      ],
      rebotRules: {
        name: [
          { required: true, message: '请输入机器人名称', trigger: 'change' },
          { max: 50, message: '机器人名称 长度不能超过 50 个字符', trigger: 'blur' }
        ],
        robotToken: [
          { required: true, message: '请输入机器人Hook', trigger: 'change' },
          { max: 255, message: '机器人Hook 长度不能超过 255 个字符', trigger: 'blur' }
        ],
        robotSecret: [
          { required: true, message: '请输入机器人密钥', trigger: 'change' },
          { max: 255, message: '机器人密钥 长度不能超过 255 个字符', trigger: 'blur' }
        ]
      },
      projectInfoRules: {
        name: [
          { required: true, message: '请输入项目名称', trigger: 'change' },
          { max: 50, message: '项目名称 长度不能超过 50 个字符', trigger: 'blur' }
        ],
        desc: [
          { max: 255, message: '项目描述 长度不能超过 255 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.selectProjectInfo()
    this.loadRobotList()
  },
  methods: {
    // 点击 生成Token
    importTestcase() {
      this.importLoading = true
      generateToken(this.token.day).then(response => {
        this.token.value = response.data.token
      })
    },
    // 查询钉钉机器人列表
    loadRobotList() {
      this.listLoading = true
      robotList(this.$store.getters.projectId).then(response => {
        this.robotListData = response.data
        this.listLoading = false
      })
    },
    // 机器人 类型 转 name
    robotNameConvert(type) {
      let robotName = ''
      this.rebotOptions.forEach(item => {
        if (item.id === type) {
          robotName = item.name
          return
        }
      })
      return robotName
    },
    // 点击添加机器人按钮
    handleRobotCreate() {
      this.robotTemp = {
        id: undefined,
        type: 1,
        projectId: this.$store.getters.projectId,
        name: '',
        robotToken: '',
        robotSecret: ''
      }
      this.dialogStatus = 'create'
      this.robotDialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['robotDataForm'].clearValidate()
      })
    },
    // 点击修改机器人按钮
    handleRobotUpdate(row) {
      this.robotTemp = Object.assign({}, row) // 复制行数据
      this.dialogStatus = 'update'
      this.robotDialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['robotDataForm'].clearValidate()
      })
    },
    // 添加机器人信息
    createRobot() {
      this.$refs['robotDataForm'].validate((valid) => {
        if (valid) {
          robotAdd(this.robotTemp).then(() => {
            this.robotDialogFormVisible = false
            this.$message({ message: '添加成功!', type: 'success' })
            this.loadRobotList()
          })
        }
      })
    },
    // 更新机器人信息
    updateRobot() {
      this.$refs['robotDataForm'].validate((valid) => {
        if (valid) {
          robotUpdate(this.robotTemp).then((res) => {
            const index = this.robotListData.findIndex(v => v.id === this.robotTemp.id)
            this.robotListData.splice(index, 1, this.robotTemp)
            this.robotDialogFormVisible = false
            this.$message({ message: '修改成功!', type: 'success' })
          })
        }
      })
    },
    // 删除机器人信息
    delRobot(row, index) {
      this.$confirm('是否删除此机器人?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        robotDel(row.id).then(response => {
          this.$message({ message: '删除成功!', type: 'success' })
          this.robotListData.splice(index, 1)
        })
      })
    },
    // 查询项目信息
    selectProjectInfo() {
      projectSelectById({
        id: this.$store.getters.projectId
      }).then(response => {
        this.projectInfo = response.data
      })
    },
    // 更新项目信息
    updateProjectInfo() {
      this.$refs['ProjectForm'].validate((valid) => {
        if (valid) {
          if (this.projectInfo.forwardMode !== 0 && (!this.projectInfo.forwardUrl || this.projectInfo.forwardUrl === '')) {
            this.$message({ message: '选择转发模式后，必须输入转发 url ！', type: 'error' })
            return
          }
          const tempData = Object.assign({}, this.projectInfo)
          projectUpdate(tempData).then(() => {
            this.$message({ message: '修改成功!', type: 'success' })
          })
        }
      })
    }
  }
}
</script>
